using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Windows.Forms;
using igp.net.DataModel;
using Parser;

namespace igp.net
{
    /// <summary>
    /// Represents the editor window.
    /// </summary>
    public partial class FormEditor : Form
    {
        private int ActivePage = -1;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public FormEditor()
        {
            InitializeComponent();

            // Leave only the page with view properties
            tabControlEditors.TabPages.Clear();
            tabControlEditors.TabPages.Add(tabPageViewEditor);
            SetActivePage(0);
        }

        /// <summary>
        /// Opens a color picker and sets a specified propery of a target object.
        /// </summary>
        /// <param name="sender">control that triggered this action - it's background will be chaged accordingly</param>
        /// <param name="target">the target object</param>
        /// <param name="property">property to be changed (must be of type Color)</param>
        private void PickColorFor(Control sender, object target, PropertyInfo property)
        {
            // Setup the dialog
            colorDialog.Color = (Color) property.GetValue(target, null);
            colorDialog.ShowDialog(this);

            // Update data and UI
            sender.BackColor = colorDialog.Color;
            property.SetValue(target, colorDialog.Color, null);

            // Render
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonLegendBackground_Click(object sender, EventArgs e)
        {
            IgpLegend legend = IgpProject.Singleton.View.Legend;
            PickColorFor((Button) sender, legend, legend.GetType().GetProperty("BackgroundColor"));
        }

        private void buttonLegendText_Click(object sender, EventArgs e)
        {
            IgpLegend legend = IgpProject.Singleton.View.Legend;
            PickColorFor((Button) sender, legend, legend.GetType().GetProperty("TextColor"));
        }

        private void buttonLegendFrame_Click(object sender, EventArgs e)
        {
            IgpLegend legend = IgpProject.Singleton.View.Legend;
            PickColorFor((Button) sender, legend, legend.GetType().GetProperty("FrameColor"));
        }

        private void buttonBackground_Click(object sender, EventArgs e)
        {
            IgpView view = IgpProject.Singleton.View;
            PickColorFor((Control) sender, view, view.GetType().GetProperty("BackgroundColor"));
        }

        private void buttonGrid_Click(object sender, EventArgs e)
        {
            IgpView view = IgpProject.Singleton.View;
            PickColorFor((Control) sender, view, view.GetType().GetProperty("GridColor"));
        }

        private void buttonAxis_Click(object sender, EventArgs e)
        {
            IgpAxes axes = IgpProject.Singleton.View.Axes;
            PickColorFor((Button) sender, axes, axes.GetType().GetProperty("LineColor"));
        }

        private void buttonResolutionRender_Click(object sender, EventArgs e)
        {
            // Open context menu with resolution choice
            contextMenuStripResolutionRender.Show(buttonResolutionRender, new Point(0, 20));
        }

        private void buttonResolutionDraw_Click(object sender, EventArgs e)
        {
            // Open context menu with resolution choice
            contextMenuStripResolutionDraw.Show(buttonResolutionDraw, new Point(0, 20));
        }

        private void FormEditor_Closing(object sender, CancelEventArgs e)
        {
            // Disables ability to actually close the form
            e.Cancel = true;
            Hide();
        }

        #region Update UI from Data Model

        /// <summary>
        /// Reads view ranges and presents that data in the editor window.
        /// </summary>
        public void ReadRanges()
        {
            IgpView View = IgpProject.Singleton.View;

            textBoxMinX.BackColor = SystemColors.Window;
            textBoxMaxX.BackColor = SystemColors.Window;
            textBoxAxisX.BackColor = SystemColors.Window;

            textBoxMinY.BackColor = SystemColors.Window;
            textBoxMaxY.BackColor = SystemColors.Window;
            textBoxAxisY.BackColor = SystemColors.Window;

            if (View.LogScaleX)
            {
                textBoxMinX.Text = View.LogMinX.ToString();
                textBoxMaxX.Text = View.LogMaxX.ToString();
                textBoxAxisX.Text = View.Axes.XCoordinateLogarythmic.ToString();
            }
            else
            {
                textBoxMinX.Text = View.MinX.ToString();
                textBoxMaxX.Text = View.MaxX.ToString();
                textBoxAxisX.Text = View.Axes.XCoordinateLinear.ToString();
            }

            if (View.LogScaleY)
            {
                textBoxMinY.Text = View.LogMinY.ToString();
                textBoxMaxY.Text = View.LogMaxY.ToString();
                textBoxAxisY.Text = View.Axes.YCoordinateLogarythmic.ToString();
            }
            else
            {
                textBoxMinY.Text = View.MinY.ToString();
                textBoxMaxY.Text = View.MaxY.ToString();
                textBoxAxisY.Text = View.Axes.YCoordinateLinear.ToString();
            }
        }

        /// <summary>
        /// Reads view properties and presents that data in the editor window.
        /// </summary>
        public void ReadViewProperities()
        {
            IgpView View = IgpProject.Singleton.View;

            textBoxMinX.BackColor = SystemColors.Window;
            textBoxMaxX.BackColor = SystemColors.Window;
            textBoxAxisX.BackColor = SystemColors.Window;

            textBoxMinY.BackColor = SystemColors.Window;
            textBoxMaxY.BackColor = SystemColors.Window;
            textBoxAxisY.BackColor = SystemColors.Window;

            textBoxGridX.BackColor = SystemColors.Window;
            textBoxLabelsX.BackColor = SystemColors.Window;
            textBoxGridY.BackColor = SystemColors.Window;
            textBoxLabelsY.BackColor = SystemColors.Window;

            textBoxResolutionDrawX.BackColor = SystemColors.Window;
            textBoxResolutionDrawY.BackColor = SystemColors.Window;
            textBoxResolutionRenderX.BackColor = SystemColors.Window;
            textBoxResolutionRenderY.BackColor = SystemColors.Window;

            textBoxLegendX.BackColor = SystemColors.Window;
            textBoxLegendY.BackColor = SystemColors.Window;


            if (View.LogScaleX)
            {
                textBoxMinX.Text = View.LogMinX.ToString();
                textBoxMaxX.Text = View.LogMaxX.ToString();
                comboBoxScaleX.SelectedIndex = 1;
                textBoxAxisX.Text = View.Axes.XCoordinateLogarythmic.ToString();
                textBoxGridX.Enabled = false;
                textBoxLabelsX.Enabled = false;
            }
            else
            {
                textBoxMinX.Text = View.MinX.ToString();
                textBoxMaxX.Text = View.MaxX.ToString();
                comboBoxScaleX.SelectedIndex = 0;
                textBoxAxisX.Text = View.Axes.XCoordinateLinear.ToString();
                textBoxGridX.Enabled = true;
                textBoxLabelsX.Enabled = true;
            }

            if (View.LogScaleY)
            {
                textBoxMinY.Text = View.LogMinY.ToString();
                textBoxMaxY.Text = View.LogMaxY.ToString();
                comboBoxScaleY.SelectedIndex = 1;
                textBoxAxisY.Text = View.Axes.YCoordinateLogarythmic.ToString();
                textBoxGridY.Enabled = false;
                textBoxLabelsY.Enabled = false;
            }
            else
            {
                textBoxMinY.Text = View.MinY.ToString();
                textBoxMaxY.Text = View.MaxY.ToString();
                comboBoxScaleY.SelectedIndex = 0;
                textBoxAxisY.Text = View.Axes.YCoordinateLinear.ToString();
                textBoxGridY.Enabled = true;
                textBoxLabelsY.Enabled = true;
            }

            textBoxGridX.Text = View.GridX.ToString();
            textBoxGridY.Text = View.GridY.ToString();
            textBoxLabelsX.Text = View.LabelX.ToString();
            textBoxLabelsY.Text = View.LabelY.ToString();
            textBoxResolutionDrawX.Text = View.VWidth.ToString();
            textBoxResolutionDrawY.Text = View.VHeight.ToString();
            textBoxResolutionRenderX.Text = View.Width.ToString();
            textBoxResolutionRenderY.Text = View.Height.ToString();
            buttonBackground.BackColor = View.BackgroundColor;
            buttonGrid.BackColor = View.GridColor;
            buttonAxis.BackColor = View.Axes.LineColor;
            checkBoxResolutionFit.Checked = View.FitDraw;

            if (View.FitDraw)
            {
                buttonResolutionDraw.Enabled = false;
                buttonResolutionRender.Enabled = false;
                textBoxResolutionDrawX.Enabled = false;
                textBoxResolutionDrawY.Enabled = false;
                textBoxResolutionRenderX.Enabled = false;
                textBoxResolutionRenderY.Enabled = false;
            }
            else
            {
                buttonResolutionDraw.Enabled = true;
                buttonResolutionRender.Enabled = true;
                textBoxResolutionDrawX.Enabled = true;
                textBoxResolutionDrawY.Enabled = true;
                textBoxResolutionRenderX.Enabled = true;
                textBoxResolutionRenderY.Enabled = true;
            }

            checkBoxGridX.Checked = View.DrawXGrid;
            checkBoxGridY.Checked = View.DrawYGrid;
            checkBoxLabelsX.Checked = View.DrawXLabels;
            checkBoxLabelsY.Checked = View.DrawYLabels;
            checkBoxAxisX.Checked = View.Axes.DrawAxisX;
            checkBoxAxisY.Checked = View.Axes.DrawAxisY;
            checkBoxLegendEnable.Checked = View.Legend.Enabled;
            textBoxLegendX.Text = View.Legend.X.ToString();
            textBoxLegendY.Text = View.Legend.Y.ToString();
            buttonLegendBackground.BackColor = View.Legend.BackgroundColor;
            buttonLegendFrame.BackColor = View.Legend.FrameColor;
            buttonLegendText.BackColor = View.Legend.TextColor;

            switch (View.LineType)
            {
                case DashStyle.Solid:
                    comboBoxGridType.SelectedIndex = 0;
                    break;
                case DashStyle.Dot:
                    comboBoxGridType.SelectedIndex = 1;
                    break;
                case DashStyle.Dash:
                    comboBoxGridType.SelectedIndex = 2;
                    break;
                case DashStyle.DashDot:
                    comboBoxGridType.SelectedIndex = 3;
                    break;
            }
        }

        /// <summary>
        /// Reads current PointSet properties and presents that data in the editor window.
        /// </summary>
        public void ReadPointSetProperties()
        {
            igpPointSet ptset = IgpProject.Singleton.CurrentPointset;
            textBoxPtSetItemName.Text = ptset.ItemName;

            //Line properities
            checkPtSetBoxDrawLines.Checked = ptset.DrawLines;
            numericUpDownPtSetLineWidth.Value = ptset.LineWidth;

            switch (ptset.LineType)
            {
                case DashStyle.Solid:
                    comboPtSetBoxLineStyle.SelectedIndex = 0;
                    break;
                case DashStyle.Dot:
                    comboPtSetBoxLineStyle.SelectedIndex = 1;
                    break;
                case DashStyle.Dash:
                    comboPtSetBoxLineStyle.SelectedIndex = 2;
                    break;
                case DashStyle.DashDot:
                    comboPtSetBoxLineStyle.SelectedIndex = 3;
                    break;
            }

            buttonPtSetLineColor.BackColor = ptset.LineColor;

            //PointProperities
            checkBoxPtSetDrawPoints.Checked = ptset.DrawPoints;
            numericUpDownPtSetPointSize.Value = ptset.PointSize;
            comboBoxPtSetPointType.SelectedIndex = (int) ptset.PointType;
            comboBoxPtSetCoordinates.SelectedIndex = (int) ptset.PointCoordinates;
            buttonPtSetFillColor.BackColor = ptset.FillColor;
            buttonPtSetFrameColor.BackColor = ptset.FrameColor;
            textBoxPtSetFilter.Text = ptset.Filter;
            ReadPointsList();
            ReadPointInteraction();

            // Setup possible drivers
            comboBoxPtSetDriver.Items.Clear();
            comboBoxPtSetDriver.Items.Add("none");

            foreach (IgpItem item in IgpProject.Singleton.Items)
            {
                if (item.TypeID == IgpItemType.Polynomial || item.TypeID == IgpItemType.Function)
                {
                    comboBoxPtSetDriver.Items.Add(item.ItemName);
                }
            }

            comboBoxPtSetDriver.SelectedIndex = ptset.Driver == null
                                                    ? 0
                                                    : comboBoxIntegBottomFunction.Items.IndexOf(ptset.Driver.ItemName);
        }

        internal void ReadPointInteraction()
        {
            igpPointSet ptset = IgpProject.Singleton.CurrentPointset;

            buttonPtSetEdit.BackColor = ptset.EditMode == IgpPointEditMode.Edit ? Color.LightSteelBlue : SystemColors.Control;
            buttonPtSetAdd.BackColor = ptset.EditMode == IgpPointEditMode.Add ? Color.LightSteelBlue : SystemColors.Control;
            buttonPtSetSelect.BackColor = ptset.EditMode == IgpPointEditMode.Select ? Color.LightSteelBlue : SystemColors.Control;
        }

        internal void ReadFunctionInteraction()
        {
            IgpFunction fun = IgpProject.Singleton.CurrentFunction;

            buttonFunctionEvaluate.BackColor = fun.EditMode == IgpFunctionInteractMode.Evaluate ? Color.LightSteelBlue : SystemColors.Control;
            buttonFunctionFindRoot.BackColor = fun.EditMode == IgpFunctionInteractMode.FindRoot ? Color.LightSteelBlue : SystemColors.Control;
            buttonFunctionFindExtremum.BackColor = fun.EditMode == IgpFunctionInteractMode.FindExtremum ? Color.LightSteelBlue : SystemColors.Control;
        }

        internal void ReadPolynomialInteraction()
        {
            igpPolynomial ptset = IgpProject.Singleton.CurrentPolynomial;

            buttonPolyEvaluate.BackColor = ptset.EditMode == IgpFunctionInteractMode.Evaluate ? Color.LightSteelBlue : SystemColors.Control;
            buttonPolyFindRoot.BackColor = ptset.EditMode == IgpFunctionInteractMode.FindRoot ? Color.LightSteelBlue : SystemColors.Control;
            buttonPolyFindExtremum.BackColor = ptset.EditMode == IgpFunctionInteractMode.FindExtremum ? Color.LightSteelBlue : SystemColors.Control;
        }

        /// <summary>
        /// Updates points list in the editor window.
        /// </summary>
        public void ReadPointsList()
        {
            igpPointSet ptset = IgpProject.Singleton.CurrentPointset;
            dataGridViewPtSet.Rows.Clear();

            //Populate List

            foreach (IgpPoint pt in ptset.Points)
            {
                dataGridViewPtSet.Rows.Add(new[] {pt.X.ToString(), pt.Y.ToString()});
            }

            //Select selected Items
            int a = 0;

            foreach (IgpPoint pt in ptset.Points)
            {
                if (pt.IsSelected) dataGridViewPtSet.Rows[a].Selected = true;
                a++;
            }
        }

        /// <summary>
        /// Reads current Polynomial properties and presents that data in the editor window.
        /// </summary>
        public void ReadPolynomialProperities()
        {
            textBoxPolyAccuracy.BackColor = SystemColors.Window;
            textBoxPolyPointsCount.BackColor = SystemColors.Window;
            textBoxPolyDrawFrom.BackColor = SystemColors.Window;
            textBoxPolyDrawTo.BackColor = SystemColors.Window;

            igpPolynomial poly = IgpProject.Singleton.CurrentPolynomial;
            textBoxPolyItemName.Text = poly.ItemName;

            //Line properities
            numericUpDownPolyLineWidth.Value = poly.LineWidth;

            switch (poly.LineType)
            {
                case DashStyle.Solid:
                    comboBoxPolyLineStyle.SelectedIndex = 0;
                    break;
                case DashStyle.Dot:
                    comboBoxPolyLineStyle.SelectedIndex = 1;
                    break;
                case DashStyle.Dash:
                    comboBoxPolyLineStyle.SelectedIndex = 2;
                    break;
                case DashStyle.DashDot:
                    comboBoxPolyLineStyle.SelectedIndex = 3;
                    break;
            }

            buttonPolyLineColor.BackColor = poly.LineColor;
            textBoxPolyDrawFrom.Text = poly.DomainLower.ToString();
            textBoxPolyDrawTo.Text = poly.DomainHigher.ToString();

            if (poly.TrendlinePoints == null)
            {
                buttonPolyUnbind.Enabled = false;
                groupBox12.Enabled = true;
            }
            else
            {
                buttonPolyUnbind.Enabled = true;
                groupBox12.Enabled = false;
            }

            ReadMonomialsList();
            ReadPolynomialInteraction();
        }

        /// <summary>
        /// Reads current Function properties and presents that data in the editor window.
        /// </summary>
        public void ReadFunctionProperities()
        {
            IgpFunction poly = IgpProject.Singleton.CurrentFunction;
            textBoxFunctionItemName.Text = poly.ItemName;

            //Line properities
            numericUpDownFunctionLineWidth.Value = poly.LineWidth;

            switch (poly.LineType)
            {
                case DashStyle.Solid:
                    comboBoxFunctionLineStyle.SelectedIndex = 0;
                    break;
                case DashStyle.Dot:
                    comboBoxFunctionLineStyle.SelectedIndex = 1;
                    break;
                case DashStyle.Dash:
                    comboBoxFunctionLineStyle.SelectedIndex = 2;
                    break;
                case DashStyle.DashDot:
                    comboBoxFunctionLineStyle.SelectedIndex = 3;
                    break;
            }

            buttonFunctionLineColor.BackColor = poly.LineColor;
            textBoxFunctionDrawFrom.Text = poly.DomainLower.ToString();
            textBoxFunctionDrawTo.Text = poly.DomainHigher.ToString();

            textBoxFunctionFormula.Text = poly.Formula.GetExpression();
            textBoxONP.Text = poly.Formula.GetONP();
            textBoxSeriesLimit.Text = poly.SeriesLowerLimit + ":" + poly.SeriesLimit;
            checkBoxSeries.Checked = poly.IsSeries;

            ReadFunctionInteraction();
        }

        /// <summary>
        /// Reads current Integral properties and presents that data in the editor window.
        /// </summary>
        public void ReadIntegralProperities()
        {
            textBoxIntegFrom.BackColor = SystemColors.Window;
            textBoxIntegTo.BackColor = SystemColors.Window;

            igpIntegral poly = IgpProject.Singleton.CurrentIntegral;
            textBoxIntegItemName.Text = poly.ItemName;

            comboBoxIntegTopFunction.Items.Clear();
            comboBoxIntegBottomFunction.Items.Clear();
            comboBoxIntegBottomFunction.Items.Add("Axis OX");

            foreach (IgpItem item in IgpProject.Singleton.Items)
            {
                if (item.TypeID == IgpItemType.Polynomial || item.TypeID == IgpItemType.Function)
                {
                    comboBoxIntegTopFunction.Items.Add(item.ItemName);
                    comboBoxIntegBottomFunction.Items.Add(item.ItemName);
                }
            }

            if (poly.BottomFunctionBase == null)
            {
                comboBoxIntegBottomFunction.SelectedIndex = 0;
            }
            else
            {
                comboBoxIntegBottomFunction.SelectedIndex =
                    comboBoxIntegBottomFunction.Items.IndexOf(poly.BottomFunctionBase.ItemName);
            }

            comboBoxIntegTopFunction.SelectedIndex = comboBoxIntegTopFunction.Items.IndexOf(poly.TopFunctionBase.ItemName);

            ReadIntegralRanges(poly);

            numericUpDownIntegOpacity.Value = poly.LineColor.A;
            numericUpDownIntegDivisions.Value = poly.Divisions;
            comboBoxIntegMethod.SelectedIndex = (int)poly.Type;
            numericUpDownIntegDivisions.Enabled = poly.Type != IgpIntegralType.Acurrate;
            buttonIntegColor.BackColor = poly.LineColor;
            ReadIntegralValues(poly);
        }

        /// <summary>
        /// Updates integral ranges in the editor window.
        /// </summary>
        /// <param name="integral">Integral</param>
        public void ReadIntegralRanges(igpIntegral integral)
        {
            textBoxIntegFrom.Text = integral.From.ToString();
            textBoxIntegTo.Text = integral.To.ToString();
        }

        /// <summary>
        /// Updates integral calulation results and presents that data in the editor window.
        /// </summary>
        /// <param name="integral">Integral</param>
        public void ReadIntegralValues(igpIntegral integral)
        {
            double val = integral.Calculate();
            textBoxIntegValue.Text = val.ToString();
            textBoxIntegAverage.Text = (val / (integral.To - integral.From)).ToString();

            double len = integral.TopLength();

            textBoxIntegTopLength.Text = len != -1 ? len.ToString() : "---";

            len = integral.BottomLength();
            textBoxIntegBottomLength.Text = len != -1 ? integral.BottomLength().ToString() : "---";
        }

        private void ReadMonomialsList()
        {
            igpPolynomial poly = IgpProject.Singleton.CurrentPolynomial;
            dataGridViewPoly.Rows.Clear();

            foreach (IgpMonomial mon in poly.Monomials)
            {
                dataGridViewPoly.Rows.Add(new object[]
                  {
                      mon.Multiplier.ToString(), mon.Exponent.ToString(), mon.Limited,
                      mon.LowerXLimit.ToString(), mon.HigherXLimit.ToString()
                  });
            }
        }

        /// <summary>
        /// Reads current Label properties and presents that data in the editor window.
        /// </summary>
        public void ReadLabelProperities()
        {
            textBoxLabelX.BackColor = SystemColors.Window;
            textBoxLabelX.BackColor = SystemColors.Window;

            IgpLabel lab = IgpProject.Singleton.CurrentLabel;
            textBoxLabelItemName.Text = lab.ItemName;
            textBoxLabelX.Text = lab.X.ToString();
            textBoxLabelY.Text = lab.Y.ToString();
            checkBoxLabelFixedX.Checked = lab.FixedX;
            checkBoxLabelFixedY.Checked = lab.FixedY;
            buttonLabelFillColor.BackColor = lab.FillColor;
            buttonLabelFrameColor.BackColor = lab.FrameColor;
            buttonLabelTextColor.BackColor = lab.TextColor;
            checkBoxLabelOnlyString.Checked = lab.DrawTextOnly;
        }

        #endregion


        /// <summary>
        /// Sets currently selected point on the list.
        /// </summary>
        /// <param name="index">Index of the point to be selected</param>
        public void SetCurrentPointOnList(int index)
        {
            dataGridViewPtSet.CurrentCell = dataGridViewPtSet[0, index];
        }

        /// <summary>
        /// Updates points' coordinates in the current PointSet with values from user input.
        /// </summary>
        public void UpdatePointsCoordinates()
        {
            IgpProject.Singleton.CurrentPointset.Points.Clear();

            foreach (DataGridViewRow row in dataGridViewPtSet.Rows)
            {
                if (!row.IsNewRow)
                {
                    IgpProject.Singleton.CurrentPointset.AddPoint(
                        double.Parse(row.Cells[0].Value.ToString()),
                        double.Parse(row.Cells[1].Value.ToString()));
                }
            }
        }

        /// <summary>
        /// Updates monomials' parameters in the current Polynomial with values from user input.
        /// </summary>
        public void UpdateMonomials()
        {
            // TODO rewrite this - monomial update
            IgpProject.Singleton.CurrentPolynomial.Monomials.Clear();

            try
            {
                foreach (DataGridViewRow row in dataGridViewPoly.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        double m = double.Parse(row.Cells[0].Value.ToString());
                        int w = int.Parse(row.Cells[1].Value.ToString());

                        IgpMonomial mon = IgpProject.Singleton.CurrentPolynomial.AddMonomial(m, w);

                        bool limited = row.Cells[2].Value != null && bool.Parse(row.Cells[2].Value.ToString());

                        if (limited)
                        {
                            if (row.Cells[3].Value == null || row.Cells[4].Value == null)
                            {
                                throw new Exception("error: if you limit a monomial you must specify the range");
                            }

                            mon.Limited = limited;

                            mon.LowerXLimit = double.Parse(row.Cells[3].Value.ToString());
                            mon.HigherXLimit = double.Parse(row.Cells[4].Value.ToString());
                        }
                        else
                        {
                            mon.LowerXLimit = 0;
                            mon.HigherXLimit = 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage("LogMessage: " + ex.Message);
            }
        }

        /// <summary>
        /// Sets the active property page.
        /// </summary>
        /// <param name="index">Page index</param>
        public void SetActivePage(int index)
        {
            if (index == ActivePage && tabControlEditors.SelectedIndex == 1) return;

            ActivePage = index;

            if (tabControlEditors.TabPages.Count == 2)
            {
                tabControlEditors.TabPages.RemoveAt(1);
            }

            switch (index)
            {
                case 0:
                    tabControlEditors.SelectedIndex = 0;
                    break;
                case 1:
                    tabControlEditors.TabPages.Add(tabPage2);
                    tabControlEditors.SelectedIndex = 1;
                    break;
                case 2:
                    tabControlEditors.TabPages.Add(tabPage3);
                    tabControlEditors.SelectedIndex = 1;
                    break;
                case 3:
                    tabControlEditors.TabPages.Add(tabPage4);
                    tabControlEditors.SelectedIndex = 1;
                    break;
                case 4:
                    tabControlEditors.TabPages.Add(tabPage5);
                    tabControlEditors.SelectedIndex = 1;
                    break;
                case 5:
                    tabControlEditors.TabPages.Add(tabPage6);
                    tabControlEditors.SelectedIndex = 1;
                    break;
            }
        }

        /// <summary>
        /// Gets the active property page index.
        /// </summary>
        /// <returns>Page index</returns>
        public int GetActivePage()
        {
            return tabControlEditors.SelectedIndex == 1 ? ActivePage : 0;
        }

        /// <summary>
        /// Checks whether there is no property tab open to edit just deleted items.
        /// </summary>
        public void VerifyTabs()
        {
            if (ActivePage == 1 && IgpProject.Singleton.CurrentPointset == null)
            {
                SetActivePage(0);
            }
            if (ActivePage == 2 && IgpProject.Singleton.CurrentFunction == null)
            {
                SetActivePage(0);
            }
            if (ActivePage == 3 && IgpProject.Singleton.CurrentPolynomial == null)
            {
                SetActivePage(0);
            }
            if (ActivePage == 4 && IgpProject.Singleton.CurrentLabel == null)
            {
                SetActivePage(0);
            }
            if (ActivePage == 5 && IgpProject.Singleton.CurrentIntegral == null)
            {
                SetActivePage(0);
            }
        }


        private void FormEditor_Load(object sender, EventArgs e)
        {
            ReadViewProperities();

            List<string> names = Expression.GetSupportedFunctions();
            names.Add("x");
            textBoxPtSetTransformation.Words = names.ToArray();
            names.Add("n");
            textBoxFunctionFormula.Words = names.ToArray();


            names = Expression.GetSupportedFunctionsDescriptions();
            names.Add("variable argument");
            textBoxPtSetTransformation.Descriptions = names.ToArray();
            names.Add("series iterator");
            textBoxFunctionFormula.Descriptions = names.ToArray();
        }

        private void comboBoxScaleX_SelectedIndexChanged(object sender, EventArgs e)
        {
            IgpView View = IgpProject.Singleton.View;

            if (comboBoxScaleX.SelectedIndex == 0)
            {
                View.LogScaleX = false;
                textBoxGridX.Enabled = true;
                textBoxLabelsX.Enabled = true;
            }
            else
            {
                View.LogScaleX = true;
                textBoxGridX.Enabled = false;
                textBoxLabelsX.Enabled = false;
            }

            if (FormMain.Singleton != null)
            {
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                FormMain.Singleton.EditorWindow.ReadRanges();
            }
        }

        private void comboBoxScaleY_SelectedIndexChanged(object sender, EventArgs e)
        {
            IgpView View = IgpProject.Singleton.View;

            if (comboBoxScaleY.SelectedIndex == 0)
            {
                View.LogScaleY = false;
                textBoxGridY.Enabled = true;
                textBoxLabelsY.Enabled = true;
            }
            else
            {
                View.LogScaleY = true;
                textBoxGridY.Enabled = false;
                textBoxLabelsY.Enabled = false;
            }

            if (FormMain.Singleton != null)
            {
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                FormMain.Singleton.EditorWindow.ReadRanges();
            }
        }

        private void checkBoxGridX_Click(object sender, EventArgs e)
        {
            if (checkBoxGridX.Checked) IgpProject.Singleton.View.DrawXGrid = true;
            if (!checkBoxGridX.Checked) IgpProject.Singleton.View.DrawXGrid = false;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxGridY_Click(object sender, EventArgs e)
        {
            if (checkBoxGridY.Checked) IgpProject.Singleton.View.DrawYGrid = true;
            if (!checkBoxGridY.Checked) IgpProject.Singleton.View.DrawYGrid = false;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxAxisX_Click(object sender, EventArgs e)
        {
            if (checkBoxAxisX.Checked) IgpProject.Singleton.View.Axes.DrawAxisX = true;
            if (!checkBoxAxisX.Checked) IgpProject.Singleton.View.Axes.DrawAxisX = false;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxAxisY_Click(object sender, EventArgs e)
        {
            if (checkBoxAxisY.Checked) IgpProject.Singleton.View.Axes.DrawAxisY = true;
            if (!checkBoxAxisY.Checked) IgpProject.Singleton.View.Axes.DrawAxisY = false;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxResolutionRenderX_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.Width = int.Parse(textBoxResolutionRenderX.Text);
                IgpProject.Singleton.UpdateResolutions();

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxResolutionRenderY_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.Height = int.Parse(textBoxResolutionRenderY.Text);
                IgpProject.Singleton.UpdateResolutions();

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxResolutionDrawX_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.VWidth = int.Parse(textBoxResolutionDrawX.Text);

                FormMain.Singleton.ClearView();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxResolutionDrawY_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.VHeight = int.Parse(textBoxResolutionDrawY.Text);

                FormMain.Singleton.ClearView();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void checkBoxResolutionFit_Click(object sender, EventArgs e)
        {
            if (checkBoxResolutionFit.Checked)
            {
                IgpProject.Singleton.View.FitDraw = true;
                FormMain.Singleton.FitViewToPanel();
                FormMain.Singleton.ClearView();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                buttonResolutionDraw.Enabled = false;
                buttonResolutionRender.Enabled = false;
                textBoxResolutionDrawX.Enabled = false;
                textBoxResolutionDrawY.Enabled = false;
                textBoxResolutionRenderX.Enabled = false;
                textBoxResolutionRenderY.Enabled = false;
            } else 
            {
                IgpProject.Singleton.View.FitDraw = false;
                buttonResolutionDraw.Enabled = true;
                buttonResolutionRender.Enabled = true;
                textBoxResolutionDrawX.Enabled = true;
                textBoxResolutionDrawY.Enabled = true;
                textBoxResolutionRenderX.Enabled = true;
                textBoxResolutionRenderY.Enabled = true;
            }
        }

        private void textBoxMaxY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (IgpProject.Singleton.View.LogScaleY)
                    IgpProject.Singleton.View.LogMaxY = Double.Parse(textBoxMaxY.Text);

                if (!IgpProject.Singleton.View.LogScaleY)
                    IgpProject.Singleton.View.MaxY = Double.Parse(textBoxMaxY.Text);

                IgpProject.Singleton.View.UpdateDistances();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxMinX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (IgpProject.Singleton.View.LogScaleX)
                    IgpProject.Singleton.View.LogMinX = Double.Parse(textBoxMinX.Text);

                if (!IgpProject.Singleton.View.LogScaleX)
                    IgpProject.Singleton.View.MinX = Double.Parse(textBoxMinX.Text);

                IgpProject.Singleton.View.UpdateDistances();

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxMinY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (IgpProject.Singleton.View.LogScaleY)
                    IgpProject.Singleton.View.LogMinY = Double.Parse(textBoxMinY.Text);

                if (!IgpProject.Singleton.View.LogScaleY)
                    IgpProject.Singleton.View.MinY = Double.Parse(textBoxMinY.Text);

                IgpProject.Singleton.View.UpdateDistances();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxMaxX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (IgpProject.Singleton.View.LogScaleX)
                    IgpProject.Singleton.View.LogMaxX = Double.Parse(textBoxMaxX.Text);

                if (!IgpProject.Singleton.View.LogScaleX)
                    IgpProject.Singleton.View.MaxX = Double.Parse(textBoxMaxX.Text);

                IgpProject.Singleton.View.UpdateDistances();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void checkBoxLegendEnable_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.View.Legend.Enabled = checkBoxLegendEnable.Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxLegendX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.Legend.X = int.Parse(textBoxLegendX.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxLegendY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.Legend.Y = int.Parse(textBoxLegendY.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxGridX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.GridX = double.Parse(textBoxGridX.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxGridY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.GridY = double.Parse(textBoxGridY.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxAxisX_KeyUp(object sender, KeyEventArgs e)
        {
            IgpView View = IgpProject.Singleton.View;

            try
            {
                if (!View.LogScaleX)
                {
                    View.Axes.XCoordinateLinear = double.Parse(textBoxAxisX.Text);
                }
                else
                {
                    View.Axes.XCoordinateLogarythmic = double.Parse(textBoxAxisX.Text);
                }

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxAxisY_KeyUp(object sender, KeyEventArgs e)
        {
            IgpView View = IgpProject.Singleton.View;

            try
            {
                if (!View.LogScaleY)
                {
                    View.Axes.YCoordinateLinear = double.Parse(textBoxAxisY.Text);
                }
                else
                {
                    View.Axes.YCoordinateLogarythmic = double.Parse(textBoxAxisY.Text);
                }

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxLabelsX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.LabelX = double.Parse(textBoxLabelsX.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxLabelsY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.View.LabelY = double.Parse(textBoxLabelsY.Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void comboBoxGridType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBoxGridType.SelectedIndex)
            {
                case 0:
                    IgpProject.Singleton.View.LineType = DashStyle.Solid;
                    break;
                case 1:
                    IgpProject.Singleton.View.LineType = DashStyle.Dot;
                    break;
                case 2:
                    IgpProject.Singleton.View.LineType = DashStyle.Dash;
                    break;
                case 3:
                    IgpProject.Singleton.View.LineType = DashStyle.DashDot;
                    break;
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonDefaults_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.View.Defaults();
            IgpProject.Singleton.UpdateResolutions();

            ReadViewProperities();

            FormMain.Singleton.ClearView();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxLabelsX_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.View.DrawXLabels = checkBoxLabelsX.Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxLabelsY_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.View.DrawYLabels = checkBoxLabelsY.Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkPtSetBoxDrawLines_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.DrawLines = ((CheckBox) sender).Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetLineColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentPointset.LineColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentPointset.LineColor = colorDialog.Color;
            buttonPtSetLineColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboPtSetBoxLineStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (((ComboBox) sender).SelectedIndex)
            {
                case 0:
                    IgpProject.Singleton.CurrentPointset.LineType = DashStyle.Solid;
                    break;
                case 1:
                    IgpProject.Singleton.CurrentPointset.LineType = DashStyle.Dot;
                    break;
                case 2:
                    IgpProject.Singleton.CurrentPointset.LineType = DashStyle.Dash;
                    break;
                case 3:
                    IgpProject.Singleton.CurrentPointset.LineType = DashStyle.DashDot;
                    break;
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxPtSetDrawPoints_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.DrawPoints = ((CheckBox) sender).Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxPtSetPointType_SelectedIndexChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.PointType = (IgpPointType) ((ComboBox) sender).SelectedIndex;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxPtSetCoordinates_SelectedIndexChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.PointCoordinates = (IgpCoordinates) ((ComboBox) sender).SelectedIndex;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetFrameColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentPointset.FrameColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentPointset.FrameColor = colorDialog.Color;
            buttonPtSetFrameColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetFillColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentPointset.FillColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentPointset.FillColor = colorDialog.Color;
            buttonPtSetFillColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetEdit_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.EditMode = IgpPointEditMode.Edit;
            ReadPointInteraction();
        }

        private void buttonPtSetAdd_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.EditMode = IgpPointEditMode.Add;
            ReadPointInteraction();
        }

        private void buttonPtSetSelect_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.EditMode = IgpPointEditMode.Select;
            ReadPointInteraction();
        }

        private void buttonPtSetFit_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.FitPointSet(IgpProject.Singleton.CurrentPointset);
            ReadRanges();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetSort_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.SortPoints();
            IgpProject.Singleton.UpdatePolynomials();

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void ApplyPointsSelection()
        {
            int a = 0;

            foreach (IgpPoint pt in IgpProject.Singleton.CurrentPointset.Points)
            {
                pt.IsSelected = dataGridViewPtSet.Rows[a++].Selected;
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void ApplyMonomialsSelection()
        {
            int a = 0;

            foreach (IgpMonomial mon in IgpProject.Singleton.CurrentPolynomial.Monomials)
            {
                mon.Selected = dataGridViewPoly.Rows[a++].Selected;
            }
        }

        private void textBoxPtSetItemName_KeyUp(object sender, KeyEventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.ItemName = ((TextBox) sender).Text;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxPtSetItemName_Leave(object sender, EventArgs e)
        {
            FormMain.Singleton.PickerWindow.RefreshList();
        }

        private void buttonPtSetTrendline_Click(object sender, EventArgs e)
        {
            contextMenuStripTrendlines.Show(buttonPtSetTrendline, new Point(0, 20));
        }

        private void buttonPolyUnbind_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.TrendlinePoints = null;
            groupBox12.Enabled = true;
            ((Button) sender).Enabled = false;
        }

        private void textBoxPolyItemName_KeyUp(object sender, KeyEventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.ItemName = ((TextBox) sender).Text;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxPolyItemName_Leave(object sender, EventArgs e)
        {
            FormMain.Singleton.PickerWindow.RefreshList();
        }

        private void comboBoxPolyLineStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (((ComboBox) sender).SelectedIndex)
            {
                case 0:
                    IgpProject.Singleton.CurrentPolynomial.LineType = DashStyle.Solid;
                    break;
                case 1:
                    IgpProject.Singleton.CurrentPolynomial.LineType = DashStyle.Dot;
                    break;
                case 2:
                    IgpProject.Singleton.CurrentPolynomial.LineType = DashStyle.Dash;
                    break;
                case 3:
                    IgpProject.Singleton.CurrentPolynomial.LineType = DashStyle.DashDot;
                    break;
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPolyLineColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentPolynomial.LineColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentPolynomial.LineColor = colorDialog.Color;
            buttonPolyLineColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxPolyDrawFrom_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentPolynomial.DomainLower = double.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxPolyDrawTo_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentPolynomial.DomainHigher = double.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxLabelItemName_KeyUp(object sender, KeyEventArgs e)
        {
            IgpProject.Singleton.CurrentLabel.ItemName = ((TextBox) sender).Text;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxLabelItemName_Leave(object sender, EventArgs e)
        {
            FormMain.Singleton.PickerWindow.RefreshList();
        }

        private void textBoxLabelX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentLabel.X = int.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxLabelY_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentLabel.Y = int.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void checkBoxLabelFixedX_Click(object sender, EventArgs e)
        {
            IgpLabel label = IgpProject.Singleton.CurrentLabel;
            label.FixedX = ((CheckBox) sender).Checked;
            IgpView view = IgpProject.Singleton.View;
            label.X = label.FixedX ? view.GetScreenCoordinateX(label.X) : view.GetRealCoordinateX((int) label.X);
            textBoxLabelX.Text = label.X.ToString();
            
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxLabelFixedY_Click(object sender, EventArgs e)
        {
            IgpLabel label = IgpProject.Singleton.CurrentLabel;
            label.FixedY = ((CheckBox) sender).Checked;
            IgpView view = IgpProject.Singleton.View;
            label.Y = label.FixedY ? view.GetScreenCoordinateY(label.Y) : view.GetRealCoordinateY((int) label.Y);

            textBoxLabelY.Text = label.Y.ToString();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void checkBoxLabelOnlyString_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentLabel.DrawTextOnly = ((CheckBox) sender).Checked;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonLabelTextColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentLabel.TextColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentLabel.TextColor = colorDialog.Color;
            buttonLabelTextColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonLabelFrameColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentLabel.FrameColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentLabel.FrameColor = colorDialog.Color;
            buttonLabelFrameColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonLabelFillColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentLabel.FillColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentLabel.FillColor = colorDialog.Color;
            buttonLabelFillColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPolyInsertPointset_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.SampleFunction(IgpProject.Singleton.CurrentPolynomial, int.Parse(textBoxPolyPointsCount.Text));

                FormMain.Singleton.PickerWindow.RefreshList();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage("error: " + ex.Message);
            }
        }

        private void textBoxFunctionItemName_KeyUp(object sender, KeyEventArgs e)
        {
            IgpProject.Singleton.CurrentFunction.ItemName = ((TextBox) sender).Text;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void textBoxFunctionItemName_Leave(object sender, EventArgs e)
        {
            FormMain.Singleton.PickerWindow.RefreshList();
        }

        private void buttonFunctionLineColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = IgpProject.Singleton.CurrentFunction.LineColor;
            colorDialog.ShowDialog();
            IgpProject.Singleton.CurrentFunction.LineColor = colorDialog.Color;
            buttonFunctionLineColor.BackColor = colorDialog.Color;
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxFunctionLineStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (((ComboBox) sender).SelectedIndex)
            {
                case 0:
                    IgpProject.Singleton.CurrentFunction.LineType = DashStyle.Solid;
                    break;
                case 1:
                    IgpProject.Singleton.CurrentFunction.LineType = DashStyle.Dot;
                    break;
                case 2:
                    IgpProject.Singleton.CurrentFunction.LineType = DashStyle.Dash;
                    break;
                case 3:
                    IgpProject.Singleton.CurrentFunction.LineType = DashStyle.DashDot;
                    break;
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonFunctionInsertPtSet_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.SampleFunction(IgpProject.Singleton.CurrentFunction, int.Parse(textBoxFunctionPointsCount.Text));

                FormMain.Singleton.PickerWindow.RefreshList();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage("error: " + ex.Message);
            }
        }

        private void buttonFunctionSetName_Click(object sender, EventArgs e)
        {
            IgpFunction fun = IgpProject.Singleton.CurrentFunction;

            try
            {
                int val = new Expression(textBoxFunctionFormula.Text, new[] { "x", "n" }).Validate();

                if (val == 0)
                {
                    fun.ItemName = textBoxFunctionFormula.Text;
                    textBoxFunctionItemName.Text = textBoxFunctionFormula.Text;
                    FormMain.Singleton.PickerWindow.RefreshList();
                    FormMain.Singleton.Render();
                    FormMain.Singleton.PaintView();
                }
            }
            catch (ParserException ex)
            {
                FormMain.Singleton.LogMessage(ex.Message);
                textBoxFunctionFormula.Focus();
                textBoxFunctionFormula.Select(ex.Start, ex.End - ex.Start);
            }
        }

        private void textBoxFunctionDrawTo_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentFunction.DomainHigher = double.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxFunctionDrawFrom_Leave(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentFunction.DomainLower = double.Parse(((TextBox) sender).Text);

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void buttonFunctionEvaluate_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentFunction.EditMode = IgpFunctionInteractMode.Evaluate;
            ReadFunctionInteraction();
        }

        private void buttonFunctionFindRoot_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentFunction.EditMode = IgpFunctionInteractMode.FindRoot;
            ReadFunctionInteraction();
        }

        private void buttonFunctionFindExtremum_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentFunction.EditMode = IgpFunctionInteractMode.FindExtremum;
            ReadFunctionInteraction();
        }

        private void buttonPolyEvaluate_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.EditMode = IgpFunctionInteractMode.Evaluate;
            ReadPolynomialInteraction();
        }

        private void buttonPolyFindRoot_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.EditMode = IgpFunctionInteractMode.FindRoot;
            ReadPolynomialInteraction();
        }

        private void buttonPolyFindExtremum_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.EditMode = IgpFunctionInteractMode.FindExtremum;
            ReadPolynomialInteraction();
        }

        /// <summary>
        /// Gets desired accuracy for root/exremum calculations. 
        /// </summary>
        /// <returns></returns>
        public double GetAccuracy()
        {
            double result = 0.001;

            try
            {
                if (GetActivePage() == 2)
                {
                    result = double.Parse(textBoxFunctionAccuracy.Text);
                }

                if (GetActivePage() == 3)
                {
                    result = double.Parse(textBoxPolyAccuracy.Text);
                }

                return result;
            }
            catch (Exception)
            {
                FormMain.Singleton.LogMessage("error: accuracy value is invalid. using defaults.");
            }

            return result;
        }

        private void textBoxIntegItemName_Leave(object sender, EventArgs e)
        {
            FormMain.Singleton.PickerWindow.RefreshList();
        }

        private void textBoxIntegItemName_KeyUp(object sender, KeyEventArgs e)
        {
            IgpProject.Singleton.CurrentIntegral.ItemName = ((TextBox) sender).Text;
        }

        private void textBoxIntegFrom_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentIntegral.From = double.Parse(((TextBox) sender).Text);

                ReadIntegralValues(IgpProject.Singleton.CurrentIntegral);
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void textBoxIntegTo_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentIntegral.To = double.Parse(((TextBox) sender).Text);

                ReadIntegralValues(IgpProject.Singleton.CurrentIntegral);
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void buttonIntegColor_Click(object sender, EventArgs e)
        {
            // Setup the dialog
            igpIntegral integral = IgpProject.Singleton.CurrentIntegral;

            colorDialog.Color = integral.LineColor;
            colorDialog.ShowDialog();

            // Update data and UI
            integral.LineColor = Color.FromArgb((int) numericUpDownIntegOpacity.Value,colorDialog.Color);
            buttonIntegColor.BackColor = integral.LineColor;

            // Render
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxIntegMethod_SelectionChangeCommitted(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentIntegral.Type = (IgpIntegralType) ((ComboBox) sender).SelectedIndex;
            ReadIntegralValues(IgpProject.Singleton.CurrentIntegral);

            numericUpDownIntegDivisions.Enabled = IgpProject.Singleton.CurrentIntegral.Type != IgpIntegralType.Acurrate;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxIntegTopFunction_SelectionChangeCommitted(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentIntegral.TopFunctionBase =
                (IgpFunctionBase) IgpProject.Singleton.GetItem(((ComboBox) sender).Text);

            ReadIntegralValues(IgpProject.Singleton.CurrentIntegral);

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void comboBoxIntegBottomFunction_SelectionChangeCommitted(object sender, EventArgs e)
        {
            igpIntegral integral = IgpProject.Singleton.CurrentIntegral;
            integral.BottomFunctionBase = ((ComboBox) sender).SelectedIndex == 0
                                              ? null
                                              : (IgpFunctionBase) IgpProject.Singleton.GetItem(((ComboBox) sender).Text);

            ReadIntegralValues(integral);

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void buttonPtSetTransform_Click(object sender, EventArgs e)
        {
            try
            {
                igpPointSet pointset = IgpProject.Singleton.CurrentPointset;
                pointset.TransformPoints(textBoxPtSetTransformation.Text, checkBoxPtSetTransformX.Checked, checkBoxPtSetTransformY.Checked);

                // Update dependent polynomials
                IgpProject.Singleton.UpdatePolynomials();

                ReadPointsList();

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (ParserException ex)
            {
                FormMain.Singleton.LogMessage(ex.Message);
                textBoxPtSetTransformation.Focus();
                textBoxPtSetTransformation.Select(ex.Start, ex.End - ex.Start);
            }
            catch(Exception ex)
            {
                FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
            }
        }

        private void comboBoxPtSetDriver_SelectionChangeCommitted(object sender, EventArgs e)
        {
            IgpProject project = IgpProject.Singleton;
            igpPointSet pointset = project.CurrentPointset;
            ComboBox comboBox = ((ComboBox) sender);

            pointset.Driver = comboBox.SelectedIndex == 0 ? null : (IgpFunctionBase) project.GetItem(comboBox.Text);
        }

        private void textBoxFunctionFormula_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                IgpFunction fun = IgpProject.Singleton.CurrentFunction;
                String old = fun.Formula.GetExpression();

                try
                {
                    fun.Formula.SetExpression(textBoxFunctionFormula.Text);
                    FormMain.Singleton.Render();
                    FormMain.Singleton.PaintView();
                    textBoxONP.Text = fun.Formula.GetONP();
                }
                catch (ParserException ex)
                {
                    fun.Formula.SetExpression(old);
                    FormMain.Singleton.LogMessage(ex.Message);
                    textBoxFunctionFormula.Focus();
                    textBoxFunctionFormula.Select(ex.Start, ex.End - ex.Start);
                }
                catch(Exception ex)
                {
                    fun.Formula.SetExpression(old);
                    FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
                }
            }
        }

        private void textBoxPtSetFilter_KeyUp(object sender, KeyEventArgs e)
        {
            if (((TextBox) sender).Text.Length == 0) return;

            IgpProject.Singleton.CurrentPointset.Filter = ((TextBox) sender).Text.ToLower();

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownIntegDivisions_ValueChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentIntegral.Divisions = (int) ((NumericUpDown) sender).Value;
            ReadIntegralValues(IgpProject.Singleton.CurrentIntegral);

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownIntegOpacity_ValueChanged(object sender, EventArgs e)
        {
            igpIntegral integral = IgpProject.Singleton.CurrentIntegral;
            integral.LineColor = Color.FromArgb((int)((NumericUpDown)sender).Value, integral.LineColor);
            buttonIntegColor.BackColor = integral.LineColor;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownPolyLineWidth_ValueChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.LineWidth = (int) ((NumericUpDown) sender).Value;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownFunctionLineWidth_ValueChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentFunction.LineWidth = (int) ((NumericUpDown) sender).Value;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownPtSetLineWidth_ValueChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.LineWidth = (int) ((NumericUpDown) sender).Value;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void numericUpDownPtSetPointSize_ValueChanged(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.PointSize = (int) ((NumericUpDown) sender).Value;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        /// <summary>
        /// Updates manual evaluation results in the editor window.
        /// </summary>
        /// <param name="x">Function argument value</param>
        public void ManualEval(double x)
        {
            if (GetActivePage() == 2)
            {
                textBoxFunctionManualEvalX.Text = x.ToString();
            }

            if (GetActivePage() == 3)
            {
                textBoxPolyManualEvalX.Text = x.ToString();
            }
        }

        private void textBoxFunctionManualEvalX_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double x = double.Parse(((TextBox) sender).Text);

                IgpFunction function = IgpProject.Singleton.CurrentFunction;

                if (x < function.DomainLower || function.DomainHigher < x)
                {
                    textBoxFunctionManualEvalFX.Text = "---";
                    return;
                }

                double y = function.Value(x);
                double dy = function.Derivative(x);

                textBoxFunctionManualEvalFX.Text = y.ToString();
                textBoxFunctionManualEvalFPX.Text = dy.ToString();
            }
            catch (Exception)
            {
                textBoxFunctionManualEvalFX.Text = "---";
                textBoxFunctionManualEvalFPX.Text = "---";
            }
        }

        private void textBoxPolyManualEvalX_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double x = double.Parse(((TextBox) sender).Text);

                igpPolynomial polynomial = IgpProject.Singleton.CurrentPolynomial;

                if (x < polynomial.DomainLower || polynomial.DomainHigher < x)
                {
                    textBoxPolyManualEvalFX.Text = "---";
                    return;
                }

                double y = polynomial.Value(x);
                double dy = polynomial.Derivative(x);

                textBoxPolyManualEvalFX.Text = y.ToString();
                textBoxPolyManualEvalFPX.Text = dy.ToString();
            }
            catch (Exception)
            {
                textBoxPolyManualEvalFX.Text = "---";
                textBoxPolyManualEvalFPX.Text = "---";
            }
        }

        private void textBoxPolyManualEvalX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                double x = double.Parse(((TextBox) sender).Text);
                IgpProject.Singleton.Cursor.Update(x);
                FormMain.Singleton.Render();
                IgpProject.Singleton.Cursor.Draw(IgpProject.Singleton.Graph);
                FormMain.Singleton.PaintView();
            }
            catch (Exception)
            {
                textBoxPolyManualEvalFX.Text = "---";
                textBoxPolyManualEvalFPX.Text = "---";
            }
        }

        private void textBoxFunctionManualEvalX_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                double x = double.Parse(((TextBox) sender).Text);
                IgpProject.Singleton.Cursor.Update(x);
                FormMain.Singleton.Render();
                IgpProject.Singleton.Cursor.Draw(IgpProject.Singleton.Graph);
                FormMain.Singleton.PaintView();
            }
            catch (Exception)
            {
                textBoxPolyManualEvalFX.Text = "---";
                textBoxPolyManualEvalFPX.Text = "---";
            }
        }

        private void buttonStore_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.BufferStore();
        }

        private void buttonRestore_Click(object sender, EventArgs e)
        {
            if (!IgpProject.Singleton.BufferReady())
            {
                FormMain.Singleton.LogMessage("error: you need to store view settings first");
                return;
            }

            IgpProject.Singleton.BufferRestore();
            ReadViewProperities();
            IgpProject.Singleton.UpdateResolutions();
            FormMain.Singleton.ClearView();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void dataGridViewPtSet_MouseUp(object sender, MouseEventArgs e)
        {
            if (dataGridViewPtSet.HitTest(e.X, e.Y).RowIndex >= 0) ApplyPointsSelection();
        }

        private void acceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdatePointsCoordinates();
            ApplyPointsSelection();
            IgpProject.Singleton.UpdatePolynomials();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points)
            {
                point.IsSelected = true;
            }

            ReadPointsList();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void selectNoneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points)
            {
                point.IsSelected = false;
            }

            ReadPointsList();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void inverseSelectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points)
            {
                point.IsSelected = !point.IsSelected;
            }

            ReadPointsList();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.Copy();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int a = IgpProject.Singleton.CurrentPointset.Paste();
                ReadPointsList();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                FormMain.Singleton.LogMessage(string.Format("Found {0} points in clipboard", a));
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage(ex.Message);
            }
        }

        private void deleteSelectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var toBeDeleted = new List<IgpPoint>();

            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points)
            {
                if (point.IsSelected) toBeDeleted.Add(point);
            }

            foreach (IgpPoint point in toBeDeleted)
            {
                IgpProject.Singleton.CurrentPointset.Points.Remove(point);
            }

            IgpProject.Singleton.UpdatePolynomials();

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();

            ReadPointsList();
        }

        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPointset.Points.Clear();
            dataGridViewPtSet.Rows.Clear();

            IgpProject.Singleton.UpdatePolynomials();

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void dataGridViewPoly_MouseUp(object sender, MouseEventArgs e)
        {
            if (dataGridViewPoly.HitTest(e.X, e.Y).ColumnIndex >= 0) ApplyMonomialsSelection();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            UpdateMonomials();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var toBeDeleted = new List<IgpMonomial>();

            foreach (IgpMonomial monomial in IgpProject.Singleton.CurrentPolynomial.Monomials)
            {
                if (monomial.Selected) toBeDeleted.Add(monomial);
            }

            foreach (IgpMonomial monomial in toBeDeleted)
            {
                IgpProject.Singleton.CurrentPolynomial.Monomials.Remove(monomial);
            }

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
            ReadMonomialsList();
        }

        private void deleteAllToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            IgpProject.Singleton.CurrentPolynomial.Monomials.Clear();

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
            ReadMonomialsList();
        }

        private void buttonPtSetSelectAll_Click(object sender, EventArgs e)
        {
            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points) point.IsSelected = true;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
            ReadPointsList();
        }

        private void buttonPtSetSelectNone_Click(object sender, EventArgs e)
        {
            foreach (IgpPoint point in IgpProject.Singleton.CurrentPointset.Points) point.IsSelected = false;

            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
            ReadPointsList();
        }

        private void SetVResolution(int newWidth, int newHeight)
        {
            IgpProject.Singleton.View.VWidth = newWidth;
            IgpProject.Singleton.View.VHeight = newHeight;
            FormMain.Singleton.ClearView();
            FormMain.Singleton.PaintView();
            ReadViewProperities();
        }

        private void SetRealResolution(int newWidth, int newHeight)
        {
            IgpProject.Singleton.View.Width = newWidth;
            IgpProject.Singleton.View.Height = newHeight;
            IgpProject.Singleton.UpdateResolutions();
            FormMain.Singleton.Render();
            FormMain.Singleton.PaintView();
            ReadViewProperities();
        }

        private void x1024ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(1280, 1024);
        }

        private void x768ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(1024, 768);
        }

        private void x600ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(800, 600);
        }

        private void x480ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(640, 480);
        }

        private void x384ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(512, 384);
        }

        private void renderResolutionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetVResolution(IgpProject.Singleton.View.Width, IgpProject.Singleton.View.Height);
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            SetRealResolution(1280, 1024);
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            SetRealResolution(1024, 768);
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            SetRealResolution(800, 600);
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            SetRealResolution(640, 480);
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            SetRealResolution(512, 384);
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            SetRealResolution(IgpProject.Singleton.View.VWidth, IgpProject.Singleton.View.VHeight);
        }

        private void linearRegressionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.AddInterpolation(IgpProject.Singleton.CurrentPointset, IgpInterpolationMode.Linear);

                FormMain.Singleton.PickerWindow.RefreshList();
                ReadPointSetProperties();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch(Exception ex)
            {
                FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
            }
        }

        private void lagrangeInterpolationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.AddInterpolation(IgpProject.Singleton.CurrentPointset, IgpInterpolationMode.Lagrange);

                FormMain.Singleton.PickerWindow.RefreshList();
                ReadPointSetProperties();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
            }
        }

        private void cubicBSplineInterpolationToolStripMenuItem_Click(object sender, EventArgs e)
        {
             try
            {
                IgpProject.Singleton.AddInterpolation(IgpProject.Singleton.CurrentPointset, IgpInterpolationMode.BSpline);

                FormMain.Singleton.PickerWindow.RefreshList();
                ReadPointSetProperties();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch(Exception ex)
            {
                FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
            }
        }

        private void cubicBSplineNormalInterpolationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.AddInterpolation(IgpProject.Singleton.CurrentPointset, IgpInterpolationMode.BSplineNormal);

                FormMain.Singleton.PickerWindow.RefreshList();
                ReadPointSetProperties();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage(string.Format("error: {0}", ex.Message));
            }
        }

        private void textBoxSeriesLimit_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                string[] numbers = textBoxSeriesLimit.Text.Split(':');

                if (numbers.Length > 2)
                {
                    throw new ArgumentException(
                        "Invalid series limit string! Use form '(min:max)' or 'max' - 0 is implicit for min.");
                }

                int min = numbers.Length == 2 ? Int32.Parse(numbers[0]) : 1;
                int max = numbers.Length == 2 ? Int32.Parse(numbers[1]) : Int32.Parse(numbers[0]);

                IgpProject.Singleton.CurrentFunction.SeriesLowerLimit = min;
                IgpProject.Singleton.CurrentFunction.SeriesLimit = max;

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();

                ((TextBox) sender).BackColor = SystemColors.Window;
            }
            catch (Exception)
            {
                ((TextBox) sender).BackColor = Color.Red;
            }
        }

        private void checkBoxSeries_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.CurrentFunction.IsSeries = ((CheckBox) sender).Checked;

                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception)
            {
            }
        }

        private void buttonFunctionAddTangent_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.AddTangent(IgpProject.Singleton.CurrentFunction, double.Parse(textBoxFunctionManualEvalX.Text));

                FormMain.Singleton.PickerWindow.RefreshList();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception)
            {
            }
        }

        private void buttonPolyAddTangent_Click(object sender, EventArgs e)
        {
            try
            {
                IgpProject.Singleton.AddTangent(IgpProject.Singleton.CurrentPolynomial, double.Parse(textBoxPolyManualEvalX.Text));

                FormMain.Singleton.PickerWindow.RefreshList();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
            }
            catch (Exception)
            {
            }
        }
    }
}